<template>
  <view></view>
</template>

<script setup lang="ts">
  import { onUnload } from '@dcloudio/uni-app';
  import { subject, subscribe, publish, unsubscribe } from '@mqtt';
  import type { Subscription } from 'rxjs';
  import { showLoading } from '@/utils/prompt';
  import { ref } from 'vue';
  /**
   * 获取加注机信息
   * @param {Number} data 提交获取加注机状态次数
   * @param {Null} timer 定时器
   * @param {Null} subscription 订阅消息信息
   * @param {String} title 加注机信息
   */
  var data = ref(0);
  const timer = ref(null);
  // data
  let subscription : Subscription = null;
  const title = ref('')
  const emit = defineEmits(['fillStatus']);
  onUnload(() => {
    if (subscription !== null) {
      subscription.unsubscribe();
    }
    delFilling();
  });
  /**
   * 接收信息
   * @property {Object} num 返回加注机信息
   */
  function viewDdata(num : any) {
    const ref = num;
    if (ref.jsondata.cmd == 'task_ready_ack' || ref.jsondata.cmd == 'circle_upload_ack') {
      title.value = ref.jsondata.cmd;
      emit('fillStatus', ref.jsondata.cmd);
      delFilling();
    }
    data.value = 0;
    deltimer();
  }
  /**
   * 提交检测加注机状态
   */
  function FillingMachine() {
    showLoading()
    deltimer();
    manyTimes();
    const fillID = uni.getStorageSync('jzjfilling')
    if (!fillID) {
      return
    }
    const pearm = {
      "jsondata": {
        "cmd": "are_you_ready"
      }
    };
    publish('formal/v1/jzj/index/client/' + fillID, pearm)
    setTimeout(() => {
      if (!title.value) {
        emit('fillStatus', '未返回信息');
        delFilling();
      }
    }, 2000)
  }
  /**
   * 订阅加注机返回信息
   */
  function manyTimes() {
    timer.value = setInterval(() => {
      data.value++;
      if (data.value < 3) {
        FillingMachine();
      } else if (data.value > 3) {
        deltimer();
        data.value = 0;
      }
    }, 1000);
  }
  /**
   * 订阅加注机返回信息
   */
  function ComeBackFilling() {
    const token = uni.getStorageSync('jzjfilling');
    const pearm = 'formal/v1/jzj/index/client/' + token;
    toSubscribe();
    subscribe(pearm);
  }
  /**
   * 取消订阅加注机信息
   */
  function delFilling() {
    toUnsubscribe();
    const token = uni.getStorageSync('jzjfilling');
    const pearm = 'formal/v1/jzj/index/client/' + token;
    unsubscribe(pearm);
  }
  /**
   * 清除定时器
   */
  function deltimer() {
    if (timer.value) {
      clearInterval(timer.value);
      timer.value = null;
    }
  }
  function toSubscribe() {
    if (subscription === null) {
      subscription = subject.subscribe(viewDdata);
    }
  }

  function toUnsubscribe() {
    subscription.unsubscribe();
    subscription = null;
  }
  defineExpose({
    FillingMachine,
    ComeBackFilling,
  });
</script>

<style></style>